package com.finalministry.server;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.finalministry.database.dao.DaoFactory;
import org.finalministry.objects.Contact;

@Path("/contacts")
public class ButtonContacts {

	@GET
	@Produces(MediaType.APPLICATION_XHTML_XML + ";charset=utf-8")
	public String loadAllContacts() throws Exception {

		List<Contact> contacts = DaoFactory.getInstance().getContactDAO().getAll();
		StringBuffer htm = new StringBuffer();

		htm.append("<div><a href=\"#\" class=\"btn btn-lg btn-default\" data-toggle=\"popover\" title=\"Popover title\" data-content=\"Double click on the contact to edit it!\">Learn how to manage the contacts</a>");
		htm.append("<table class=\"table\">");

		for (Contact contact : contacts) {
			htm.append("<tr class=\"contact\"><td>");
			htm.append(contact.getAddress().getStreet());
			htm.append("</td><td>");
			htm.append(contact.getAddress().getHousenumber());
			htm.append("</td><td>");
			htm.append(contact.getAddress().getPostalcode());
			htm.append("</td><td>");
			htm.append(contact.getAddress().getCity());
			htm.append("</td><td>");
			htm.append(contact.getLastName());
			htm.append("</td></tr>");
		}

		htm.append("</table></div><div id=\"contactsDiv\"></div>");
		htm.append("<script>FM.initContacts();</script>");

		return htm.toString();
	}

	@Path("/editdialog/{id}")
	@GET
	@Produces(MediaType.APPLICATION_XHTML_XML + ";charset=utf-8")
	public String showContactEditDialog() throws IOException {

		return FileUtils.readFileToString(new File("src/main/resources/web/dialogContactEdit.htm")).replaceAll("#HOME#",
				FinalministryWebServer.contentUrl);
	}
}
